package com.mzj.saas.mservice.smartlock.service.luoke;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.entity.SmartLockBle;
import com.mzj.saas.mservice.lock.entity.SmartLockCard;
import com.mzj.saas.mservice.lock.entity.SmartLockFace;
import com.mzj.saas.mservice.lock.entity.SmartLockPwd;
import com.mzj.saas.mservice.smartlock.base.BaseLock;
import com.mzj.saas.mservice.smartlock.vo.SmartLockFingerprintVO;
import com.mzj.saas.mservice.smartlock.vo.SmartLockVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Dell
 * @Date 2024/1/24
 **/
@Slf4j
@Service
public class SmartLockLkService implements BaseLock {
    @Value("${luoke.url}")
    private String luoKeUrl;
    @Value(("${luoke.appKey}"))
    private String luoKeAppKey;
    @Value("${luoke.appSecret}")
    private String luoKeAppSecret;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OSSClient ossClient;

    @Override
    public ResultBean<String> authorizationPwd(SmartLockVO vo, SmartLockPwd smartLockPwd) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("络克--授权用户密码接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            HttpResponse response = this.addAuth(token, vo.getSn(), 1, vo.getPassword(), smartLockPwd.getStartTime(), smartLockPwd.getEndTime());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取授权信息的id
                    JSONObject data = jsonObject.getJSONObject("data");
                    objectResultBean.setResultData(data.getString("lockKeyId"));
                    return objectResultBean;
                } else {
                    log.error("络克--授权用户密码请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("添加失败：" + jsonObject.getString("message"));
                }
            } else {
                log.error("络克--授权用户密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加密码信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加密码信息请求异常");
            log.error("络克--授权用户密码请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> deletePwd(SmartLockVO vo, Long lockAuthId) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            objectResultBean.setMsg("获取token失败");
            log.error("络克--删除门锁密码接口--token为空");
            return objectResultBean;
        }
        try {
            HttpResponse response = this.removeAuth(vo.getIdentification(), token);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(vo.getIdentification());
                    return objectResultBean;
                } else {
                    objectResultBean.setMsg("删除密码失败");
                    log.error("络克--删除门锁密码请求响应数据异常：{}", jsonObject);
                }
            } else {
                objectResultBean.setMsg("删除密码响应失败");
                log.error("络克--删除门锁密码请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除密码请求异常");
            log.error("络克--删除门锁密码请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> fingerprintUnlocking(SmartLockFingerprintVO vo) {
        return null;
    }

    @Override
    public ResultBean<String> deleteFingerprintUnlocking(SmartLockVO vo) {
        return null;
    }

    @Override
    public boolean doorCardUnlocking() {
        return false;
    }

    @Override
    public ResultBean<String> identityCardUnlocking(SmartLockVO vo, SmartLockCard smartLockCard) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("络克--授权智能锁用户--门卡接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            HttpResponse response = this.addAuth(token, vo.getSn(), 2, smartLockCard.getCardNumber(), smartLockCard.getStartTime(), smartLockCard.getEndTime());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取授权信息的id
                    JSONObject data = jsonObject.getJSONObject("data");
                    objectResultBean.setResultData(data.getString("lockKeyId"));
                    return objectResultBean;
                } else {
                    log.error("络克--授权门锁用户--门卡请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("添加失败：" + jsonObject.getString("message"));
                }
            } else {
                log.error("络克--授权门锁用户--门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加门卡信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加门卡信息请求异常");
            log.error("络克--授权门锁用户--门卡请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> deleteIdentityCardUnlocking(SmartLockVO vo) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            objectResultBean.setMsg("获取token失败");
            log.error("络克--删除门锁--门卡接口--token为空");
            return objectResultBean;
        }
        try {
            HttpResponse response = this.removeAuth(vo.getIdentification(), token);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(vo.getIdentification());
                    return objectResultBean;
                } else {
                    objectResultBean.setMsg("删除门卡失败");
                    log.error("络克--删除门锁--门卡请求响应数据异常：{}", jsonObject);
                }
            } else {
                objectResultBean.setMsg("删除门卡响应失败");
                log.error("络克--删除门锁--门卡请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除门卡请求异常");
            log.error("络克--删除门锁--门卡请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> bluetoothUnlocking(SmartLockVO vo, SmartLockBle smartLockBle) {
        return null;
    }

    @Override
    public ResultBean<String> getBluetoothUnlocking(Long lockAuthId) {
        return null;
    }

    /**
     * 获取蓝牙密钥
     *
     * @return
     */
    public ResultBean<String> getBluetoothUnlocking(String sn) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("络克--获取蓝牙密钥接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {
            log.info("络克--获取蓝牙密钥接口--授权请求参数：{}，token：{}", sn, token);
            long start = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(luoKeUrl + "/api/device/lock/instruct/operate/open_door")
                    .header("Authorization", token).header("action", "1")
                    .form("deviceId", sn).timeout(20000).execute();
            //耗时
            long elapsedTime = System.currentTimeMillis() - start;
            log.info("络克--获取蓝牙密钥接口--响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                objectResultBean.setMsg("操作成功");
                objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                objectResultBean.setResultData(response.body());
                return objectResultBean;
            } else {
                log.error("络克--获取蓝牙密钥接口请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加门卡信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("获取蓝牙密钥接口请求异常");
            log.error("络克--获取蓝牙密钥接口请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    @Override
    public ResultBean<String> deleteBluetoothUnlocking(SmartLockVO vo) {
        return null;
    }

    @Override
    public ResultBean<String> deleteAll(String mac, Long lockId) {
        return null;
    }

    public Date addTime(Date nowTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowTime);
        calendar.add(Calendar.YEAR, 50);
        return calendar.getTime();
    }

    public String getToken() {
        String token = redisTemplate.opsForValue().get("sys_luoKeToken");

        if (StrUtil.isBlank(token)) {
            try {
                Map<String, Object> paramsMap = new HashMap<>(2);
                paramsMap.put("appKey", luoKeAppKey);
                paramsMap.put("appSecret", luoKeAppSecret);
                log.info("络克--鉴权接口请求参数：{}", paramsMap);
                long start = System.currentTimeMillis();
                HttpResponse response = HttpRequest.post(luoKeUrl + "/dev/developer/get_access_token").form(paramsMap).timeout(20000).execute();
                //耗时
                long elapsedTime = System.currentTimeMillis() - start;
                log.info("络克--鉴权接口响应耗时：{}毫秒，参数：{}", elapsedTime, response.body());
                if (HttpStatus.HTTP_OK == response.getStatus()) {
                    JSONObject jsonObject = JSONObject.parseObject(response.body());
                    int code = jsonObject.getInteger("code");
                    if (HttpStatus.HTTP_OK == code) {
                        JSONObject result = jsonObject.getJSONObject("data");
                        token = result.getString("token");
                        Integer expiresTime = result.getInteger("expiresTime");
                        redisTemplate.opsForValue().set("sys_luoKeToken", token, expiresTime - elapsedTime - 5, TimeUnit.SECONDS);
                    } else {
                        log.error("络克--鉴权请求响应数据异常：{}", jsonObject);
                    }
                } else {
                    log.error("络克--鉴权请求失败，code：{}；body:{}", response.getStatus(), response.body());
                }
            } catch (Exception e) {
                log.error("络克--鉴权请求异常：{}", e.getMessage(), e);
            }
        }
        return token;
    }

    /**
     * 添加门锁钥匙
     *
     * @param token     token
     * @param deviceId  设备id-设备mac-设备sn
     * @param keyType   授权密码的类型 1:密码 2：卡片 3：指纹 90: 人脸
     * @param keyValue  密码内容值（人脸的话为人脸上传后返回的路径）
     * @param startTime 钥匙有效开始时间
     * @param endTime   钥匙有效结束时间
     * @return
     */
    public HttpResponse addAuth(String token, String deviceId, Integer keyType, String keyValue, Date startTime, Date endTime) {
        Map<String, Object> paramsMap = new HashMap<>(6);
        paramsMap.put("deviceId", deviceId);
        paramsMap.put("keyType", keyType);
        //钥匙时效类型 1:长效 2: 时段
        paramsMap.put("agingType", 2);
        paramsMap.put("keyValue", keyValue);
        paramsMap.put("startTime", startTime == null ? new Date().getTime() : startTime.getTime());
        paramsMap.put("endTime", endTime == null ? this.addTime(new Date()).getTime() : endTime.getTime());
        log.info("络克--添加门锁钥匙接口--授权请求参数：{}", paramsMap);
        long start = System.currentTimeMillis();
        HttpResponse response = HttpRequest.post(luoKeUrl + "/api/device/lock/instruct/operate/add_lock_key")
                .header("Authorization", token).header("action", "2")
                .form(paramsMap).timeout(20000).execute();
        //耗时
        long elapsedTime = System.currentTimeMillis() - start;
        log.info("络克--添加门锁钥匙接口--授权响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
        return response;
    }

    /**
     * 修改门锁钥匙
     *
     * @param token          token
     * @param identification 门锁钥匙id--身份标识
     * @param keyValue       密码值内容
     * @param startTime      钥匙有效开始时间
     * @param endTime        钥匙有效结束时间
     * @return
     */
    public HttpResponse updateAuth(String token, String identification, String keyValue, Date startTime, Date endTime) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("lockKeyId", identification);
        //钥匙时效类型 1:长效 2: 时段
        paramsMap.put("agingType", 2);
        paramsMap.put("keyValue", keyValue);
        if (startTime != null && endTime != null) {
            paramsMap.put("startTime", startTime.getTime());
            paramsMap.put("endTime", endTime.getTime());
        }
        log.info("络克--修改门锁钥匙接口密码请求参数：{}", paramsMap);
        long start = System.currentTimeMillis();
        HttpResponse response = HttpRequest.post(luoKeUrl + "/api/device/lock/instruct/operate/edit_lock_key")
                .header("Authorization", token).header("action", "2")
                .form(paramsMap).timeout(20000).execute();
        //耗时
        long elapsedTime = System.currentTimeMillis() - start;
        log.info("络克--修改门锁钥匙接口密码响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
        return response;
    }

    /**
     * 删除门锁钥匙
     *
     * @param identification 门锁钥匙id--身份标识
     * @param token          token
     * @return
     */
    public HttpResponse removeAuth(String identification, String token) {
        log.info("络克--删除门锁钥匙接口密码请求参数：{}", identification);
        long start = System.currentTimeMillis();
        HttpResponse response = HttpRequest.post(luoKeUrl + "/api/device/lock/instruct/operate/del_lock_key")
                .header("Authorization", token).header("action", "2")
                .form("lockKeyId", identification).timeout(20000).execute();
        //耗时
        long elapsedTime = System.currentTimeMillis() - start;
        log.info("络克--删除门锁钥匙接口密码响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
        return response;
    }

    /**
     * 新增授权人脸信息
     *
     * @param smartLockFace 人脸信息
     * @return
     */
    public ResultBean<String> addFaceImage(SmartLockFace smartLockFace) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("络克--授权智能锁用户--人脸接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        ResultBean<String> stringResultBean = this.uploadFile(token, smartLockFace.getFaceImage());
        if (StatusCode.ERROR_CODE_10001.getErrorCode().equals(stringResultBean.getCode())) {
            return stringResultBean;
        }
        try {
            HttpResponse response = this.addAuth(token, smartLockFace.getSn(), 90, stringResultBean.getResultData(), smartLockFace.getStartTime(), smartLockFace.getEndTime());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取授权信息的id
                    JSONObject data = jsonObject.getJSONObject("data");
                    objectResultBean.setResultData(data.getString("lockKeyId"));
                    return objectResultBean;
                } else {
                    log.error("络克--授权门锁用户--人脸请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("添加失败：" + jsonObject.getString("message"));
                }
            } else {
                log.error("络克--授权门锁用户--人脸请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加人脸信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加人脸信息请求异常");
            log.error("络克--授权门锁用户--人脸请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    public ResultBean<String> updateFaceImage(SmartLockFace smartLockFace) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("络克--授权智能锁用户--人脸接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        ResultBean<String> stringResultBean = this.uploadFile(token, smartLockFace.getFaceImage());
        if (StatusCode.ERROR_CODE_10001.getErrorCode().equals(stringResultBean.getCode())) {
            return stringResultBean;
        }
        try {
            HttpResponse response = this.updateAuth(token, smartLockFace.getIdentification(), stringResultBean.getResultData(), smartLockFace.getStartTime(), smartLockFace.getEndTime());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取授权信息的id
                    JSONObject data = jsonObject.getJSONObject("data");
                    return objectResultBean;
                } else {
                    log.error("络克--授权门锁用户--人脸请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg("添加失败：" + jsonObject.getString("message"));
                }
            } else {
                log.error("络克--授权门锁用户--人脸请求失败，code：{}；body:{}", response.getStatus(), response.body());
                objectResultBean.setMsg("添加人脸信息响应错误");
            }
        } catch (Exception e) {
            objectResultBean.setMsg("添加人脸信息请求异常");
            log.error("络克--授权门锁用户--人脸请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    /**
     * 删除授权人脸信息
     *
     * @param smartLockFace 授权人脸信息
     * @return
     */
    public ResultBean<String> deleteFaceImage(SmartLockFace smartLockFace) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            objectResultBean.setMsg("获取token失败");
            log.error("络克--删除钥匙--人脸接口--token为空");
            return objectResultBean;
        }
        try {
            HttpResponse response = this.removeAuth(smartLockFace.getIdentification(), token);
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    objectResultBean.setResultData(smartLockFace.getIdentification());
                    return objectResultBean;
                } else {
                    objectResultBean.setMsg("删除人脸失败");
                    log.error("络克--删除钥匙--人脸请求响应数据异常：{}", jsonObject);
                }
            } else {
                objectResultBean.setMsg("删除人脸响应失败");
                log.error("络克--删除钥匙--人脸请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            objectResultBean.setMsg("删除人脸请求异常");
            log.error("络克--删除钥匙--人脸请求异常：{}", e.getMessage(), e);
        }
        return objectResultBean;
    }

    /**
     * 人脸上传接口
     *
     * @param token    token
     * @param imageUrl 人脸路径
     * @return
     */
    public ResultBean<String> uploadFile(String token, String imageUrl) {
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        try {

            log.info("络克--人脸上传接口--请求参数：{}", imageUrl);
            //获取图片二进制
            imageUrl = imageUrl.split("https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/")[1];
            OSSObject object = ossClient.getObject("xj-saas-images", imageUrl);
            File file = File.createTempFile("stream2file", ".jpg");
            try (FileOutputStream out = new FileOutputStream(file)) {
                IOUtils.copy(object.getObjectContent(), out);
            }

            long start = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(luoKeUrl + "/api/localStorage/face")
                    .header("Authorization", token)
                    .form("file", file).timeout(20000).execute();
            //耗时
            long elapsedTime = System.currentTimeMillis() - start;
            log.info("络克--人脸上传接口--响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取图片上传的url
                    objectResultBean.setResultData(jsonObject.getJSONObject("data").getString("url"));
                    return objectResultBean;
                } else {
                    log.error("络克--人脸上传接口--响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg(jsonObject.getString("detailMessage"));
                }
            } else {
                log.error("络克--人脸上传接口--请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("络克--人脸上传接口--请求异常：{}", e.getMessage(), e);
            objectResultBean.setMsg(e.getMessage());
        }
        return objectResultBean;
    }

    /**
     * 根据设备id查询设备详细信息
     *
     * @param deviceId 设备id
     */
    public ResultBean<String> getLockDetail(String deviceId) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            objectResultBean.setMsg("获取token失败");
            log.error("络克--查询设备详细信息接口--token为空");
            return objectResultBean;
        }
        try {

            log.info("络克--查询设备详细信息接口--请求参数：{}", deviceId);
            long start = System.currentTimeMillis();
            HttpResponse response = HttpRequest.get(luoKeUrl + "/api/devicelock/detail")
                    .header("Authorization", token)
                    .form("deviceId", deviceId).timeout(20000).execute();
            //耗时
            long elapsedTime = System.currentTimeMillis() - start;
            log.info("络克--查询设备详细信息接口响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取图片上传的url
                    objectResultBean.setResultData(jsonObject.getString("data"));
                    return objectResultBean;
                } else {
                    log.error("络克--查询设备详细信息接口--请求响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg(jsonObject.getString("detailMessage"));
                }
            } else {
                log.error("络克--查询设备详细信息接口--请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("络克--查询设备详细信息接口--请求异常：{}", e.getMessage(), e);
            objectResultBean.setMsg(e.getMessage());
        }
        return objectResultBean;
    }

    /**
     * 改变门锁钥匙状态
     *
     * @param identification 门锁钥匙id--身份标识
     * @param stateFlag      状态 true：启用 false：禁用
     * @return
     */
    public ResultBean<String> updateKeyState(String identification, Boolean stateFlag) {
        String token = this.getToken();
        ResultBean<String> objectResultBean = new ResultBean<>();
        objectResultBean.setMsg("操作失败");
        objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (StrUtil.isEmpty(token)) {
            log.error("络克--改变门锁钥匙状态接口--token为空");
            objectResultBean.setMsg("获取token失败");
            return objectResultBean;
        }
        try {

            log.info("络克--改变门锁钥匙状态接口--请求参数：{}、{}", identification, stateFlag);

            long start = System.currentTimeMillis();
            HttpResponse response = HttpRequest.post(luoKeUrl + "/api/device/lock/instruct/operate/change_key_state")
                    .header("Authorization", token).header("action", "2")
                    .form("lockKeyId", identification).form("stateFlag", stateFlag)
                    .timeout(20000).execute();
            //耗时
            long elapsedTime = System.currentTimeMillis() - start;
            log.info("络克--改变门锁钥匙状态接口--响应耗时：{}毫秒，响应参数：{}", elapsedTime, response.body());
            if (HttpStatus.HTTP_OK == response.getStatus()) {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                int code = jsonObject.getInteger("code");
                if (HttpStatus.HTTP_OK == code) {
                    objectResultBean.setMsg("操作成功");
                    objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                    //获取图片上传的url
                    objectResultBean.setResultData(identification);
                    return objectResultBean;
                } else {
                    log.error("络克--改变门锁钥匙状态接口--响应数据异常：{}", jsonObject);
                    objectResultBean.setMsg(jsonObject.getString("detailMessage"));
                }
            } else {
                log.error("络克--改变门锁钥匙状态接口--请求失败，code：{}；body:{}", response.getStatus(), response.body());
            }
        } catch (Exception e) {
            log.error("络克--改变门锁钥匙状态接口--请求异常：{}", e.getMessage(), e);
            objectResultBean.setMsg(e.getMessage());
        }
        return objectResultBean;
    }
}
